package com.tsingteng.cosfun.utils;

import android.content.Context;
import android.support.annotation.NonNull;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadQueueSet;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述 :
 * 创建人: 肖利.
 * 时间:2018/8/13
 * qq(872179966)
 */

public class FileDownUtils {
    private static final String TAG = "FileDownUtils";

    private static FileDownUtils INSTANCE = null;
    private int downNum = 0;
    private List<String> list = new ArrayList<>();
    private boolean isAdd = false;

    private FileDownUtils() {
    }


    public static FileDownUtils getIntance() {
        if (INSTANCE == null) {
            synchronized (FileDownUtils.class) {
                if (INSTANCE == null) {
                    INSTANCE = new FileDownUtils();
                }
            }
        }

        return INSTANCE;
    }

    /**
     * @param context
     * @param url     下载的路径
     * @param path    存放的路径
     */
    public void starSingleDown(Context context, String url, String path, OnCompleteListener onCompleteListener) {
        FileDownloader.setup(context);
        FileDownloader.getImpl().create(url)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        if (onCompleteListener != null) {
                            onCompleteListener.onStart();
                        }
                        LogUtils.i("pending" + "FileDownloadListener");
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        LogUtils.i("connected" + "FileDownloadListener");
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        LogUtils.i("progress" + soFarBytes + "FileDownloadListener" + totalBytes);
                        if (onCompleteListener != null) {
                            int i = soFarBytes * 100 / totalBytes;
                            onCompleteListener.onPregress(i);
                        }
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        LogUtils.i("blockComplete" + "FileDownloadListener");

                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                        LogUtils.i("retry" + "FileDownloadListener");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        if (list.size() != 0) {
                            downNum++;
                            if (list.size() == downNum) {
                                if (onCompleteListener != null) {
                                    onCompleteListener.onComplete();
                                    list.clear();
                                    downNum = 0;
                                }
                            }
                        } else {
                            if (onCompleteListener != null) {
                                onCompleteListener.onComplete();
                            }
                        }

                        LogUtils.i("completed" + "FileDownloadListener");
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        LogUtils.i("paused" + "FileDownloadListener");
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        if (onCompleteListener != null) {
                            onCompleteListener.onError();
                        }
                        ToastUtils.showToast("下载出错!");
                        LogUtils.i("error" + e.getMessage() + "FileDownloadListener");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        LogUtils.i("warn" + "FileDownloadListener");
                    }
                }).start();
    }


    public interface OnCompleteListener {
        void onComplete();

        void onStart();

        void onPregress(int progress);

        void onError();
    }


    public interface DownloadCallBack {
        void onCompleted(String filename);

        void onProgress(int progress, int speed);


        void onNumProgress(int progress, int downNum, int totalNum, int speed);

        void onFail(String error);
    }

    private static int totalNum = 0;

    /**
     * 多任务下载
     * @param urls
     * @param savePaths
     * @param context
     * @param callBack
     */
    public  void startMoreDown( Context context,final List<String> urls, List<String> savePaths, final DownloadCallBack callBack) {
        if (urls == null || savePaths == null || urls.size() == 0 || urls.size()
                != savePaths.size()) {
            callBack.onCompleted("");
            return;
        }
        final List<String> actUrls = new ArrayList<>();
        List<String> actPaths = new ArrayList<>();
        File file = null;
        int j = 0;
        for (String p : savePaths) {
            file = new File(p);
            if (!file.exists()) {
                actUrls.add(urls.get(j));
                actPaths.add(p);
            }
            j++;
        }
        if (actPaths.size() == 0) {
            callBack.onCompleted("");
            return;
        }
        FileDownloader.setup(context);
        totalNum = actUrls.size();
        final FileDownloadListener downloadListener = new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }

            @Override
            protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                totalNum--;
                //多文件下载时，每下载一个文件，回调一次completed
                if (totalNum <= 0) {
                    callBack.onCompleted(task.getTargetFilePath());
                } else {
                    int downNum = actUrls.size() - totalNum;
                    callBack.onNumProgress((int) ((float) downNum / actUrls.size() * 100), downNum, actUrls.size(), task.getSpeed());
                }
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                callBack.onFail(e.toString());
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        };

        final FileDownloadQueueSet queueSet = new FileDownloadQueueSet(downloadListener);

        final List<BaseDownloadTask> tasks = new ArrayList<>();
        try {
            for (int i = 0; i < urls.size(); i++) {
                tasks.add(FileDownloader.getImpl().create(urls.get(i)).setPath(actPaths.get(i)).setTag(i + 1));
            }
        }catch (IndexOutOfBoundsException e) {
            LogUtils.e(TAG,e.getMessage());
        }
        // 由于是队列任务, 这里是我们假设了现在不需要每个任务都回调`FileDownloadListener#progress`, 我们只关系每个任务是否完成, 所以这里这样设置可以很有效的减少ipc.
        queueSet.disableCallbackProgressTimes();
        // 所有任务在下载失败的时候都自动重试一次
        queueSet.setAutoRetryTimes(1);
        queueSet.downloadTogether(tasks);
        queueSet.start();
    }
}
